package cn.xxstudy.blog.controller.admin

import cn.xxstudy.blog.bean.Msg
import cn.xxstudy.blog.entity.Category
import cn.xxstudy.blog.entity.Tags
import cn.xxstudy.blog.service.TagsService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.data.web.PageableDefault
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.servlet.mvc.support.RedirectAttributes
import javax.validation.Valid

/**
 * 作者：wuxinxi on 2020/11/26
 * 包名：cn.xxstudy.blog.controller.admin
 * TODO:标签管理
 */
@Controller
@RequestMapping("/admin")
class ManagerTagController {
    companion object {
        private const val MANAGER_TAG_LIST = "admin/manager-blog-tags"
        private const val MANAGER_TAG_EDIT = "admin/manager-blog-tags-edit"
    }

    @Autowired
    private lateinit var tagsService: TagsService

    @GetMapping("/tags")
    fun tagList(@PageableDefault(sort = ["id"], direction = Sort.Direction.DESC) pageable: Pageable,
                model: Model): String {
        model.addAttribute("tagsPage", tagsService.listTags(pageable))
        return MANAGER_TAG_LIST
    }

    /**
     * 标签-新建
     */
    @GetMapping("/tags/create")
    fun createCategory(model: Model): String {
        model.addAttribute("tags", Tags())
        return MANAGER_TAG_EDIT
    }

    /**
     * 标签-新建-POST 提交
     */
    @PostMapping("/tags/create")
    fun createCategoryPost(@Valid tags: Tags, result: BindingResult,
                           redirectAttributes: RedirectAttributes): String {
        val tg = tagsService.getTagsByName(tags.tagName)
        if (tg != null) {
            result.rejectValue("tagName", "tagNameRepeat", "${tags.tagName} 标签已存在")
        }
        if (result.hasErrors()) {
            return MANAGER_TAG_EDIT
        }
        val tgRep = tagsService.createTags(tags)
        redirectAttributes.addFlashAttribute("response", "${tags.tagName} 类型添加${if (tgRep == null) "失败" else "成功"}")
        return "redirect:/admin/tags"
    }


    /**
     * 编辑
     */
    @GetMapping("/tags/{id}/create")
    fun editCategory(@PathVariable id: Long, model: Model): String {
        model.addAttribute("tags", tagsService.getTagsById(id))
        return MANAGER_TAG_EDIT
    }

    /**
     * @category 编辑后的
     * @categoryName 编辑前
     */
    @PostMapping("/tags/{tagName}")
    fun editCategoryPost(@Valid tags: Tags, result: BindingResult, @PathVariable tagName: String,
                         model: Model, redirectAttributes: RedirectAttributes): String {
        val tg = tagsService.getTagsByName(tags.tagName)
        if (tg != null) {
            result.rejectValue("tagName", "tagNameRepeat", "${tags.tagName} 标签已存在")
            return MANAGER_TAG_EDIT
        }
        val success = tagsService.updateByName(tagName, tags)
        redirectAttributes.addFlashAttribute("msg",
                if (success) Msg(true, "$tagName 修改为 ${tags.tagName}修改成功")
                else Msg(false, "$tagName 修改为${tags.tagName}修改失败"))
        return "redirect:/admin/tags"
    }

    //TODO 待优化：仅刷新当前页面
    @GetMapping("/tags/delete/{tagName}")
    fun delete(@PathVariable tagName: String, redirectAttributes: RedirectAttributes): String {
        val deleteByName = tagsService.deleteByName(tagName)
        redirectAttributes.addFlashAttribute("msg",
                if (deleteByName) Msg(true, "$tagName 删除成功")
                else Msg(false, "$tagName 删除失败"))
        return "redirect:/admin/tags"
    }

}